<template>
	<div class="game-container agentList-container">
		<div class="tree-container">
			<div class="filter-search-box">
				<el-input
					clearable
					v-model="filterAccountQueryData.name"
					v-input="{ name: 'symbols' }"
					size="mini"
					:placeholder="$t('common.please_enter')"
					class="filter-search-text"
				>
					<el-select
						slot="prepend"
						v-model="filterAccountQueryData.nameType"
						:placeholder="$t('agent.query_type')"
						style="width: 100px;"
					>
						<el-option
							v-for="item in filterAccountTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-input>
				<el-button
					type="success"
					size="mini"
					class="filter-search-btn"
					@click="searchUnderAgent"
				>
					{{ $t('common.search') }}
				</el-button>
			</div>
			<div
				v-loading="agentLoading"
				element-loading-spinner="el-icon-loading"
				class="tree-box"
			>
				<!-- 全量树 -->
				<el-tree
					v-if="treeType === 'all'"
					ref="tree"
					key="agentListId"
					:props="defaultProps"
					:highlight-current="true"
					node-key="id"
					:load="loadNode"
					:default-expanded-keys="expandedKeys"
					:lazy="true"
					@node-click="nodeClick"
				>
					<span slot-scope="{ node, data }" class="custom-tree-node">
						<span>
							<i class="el-icon-user-solid" />
							{{ node.label }} {{ data.directlyUnderProxyNum }}/{{
								data.underProxyNum
							}}
						</span>
					</span>
				</el-tree>

				<!-- 搜索树 -->
				<el-tree
					v-if="treeType === 'search'"
					ref="treeSearch"
					key="treeSearch"
					:props="defaultProps"
					:highlight-current="true"
					node-key="id"
					:load="loadNode2"
					:data="treeSearchData"
					:lazy="true"
					:default-expanded-keys="expandedKeys"
					@node-click="nodeClick"
				>
					<span slot-scope="{ node, data }" class="custom-tree-node">
						<span>
							<i class="el-icon-user-solid" />
							{{ node.label }} {{ data.directlyUnderProxyNum }}/{{
								data.underProxyNum
							}}
						</span>
					</span>
				</el-tree>
			</div>
		</div>

		<main-content
			classType="agentList"
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					label-width="auto"
				>
					<el-form-item
						:label="$t('common.belong_merchant') + ':'"
						prop="merchantId"
					>
						<merchant-select
							v-model="queryData.merchantId"
						></merchant-select>
					</el-form-item>
					<el-form-item class="snap-form-item">
						<el-select
							v-model="queryData.timeType"
							size="medium"
							style="width:130px"
						>
							<el-option
								v-for="item in filterTimeTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
						<el-date-picker
							v-model="queryData.registerTime"
							size="medium"
							:picker-options="pickerShortcut2"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_time')"
							align="right"
							clearable
							value-format="timestamp"
							:default-time="defaultTime"
						></el-date-picker>
					</el-form-item>

					<el-form-item>
						<el-select
							v-model="queryData.nameType"
							style="width: 120px"
							:placeholder="$t('common.please_choose')"
						>
							<el-option
								:label="$t('agent.agent_account')"
								:value="1"
							></el-option>
							<el-option
								:label="$t('agent.total_agent_account')"
								:value="2"
							></el-option>
						</el-select>
						<el-input
							v-input="{ name: 'symbols' }"
							v-model="queryData.name"
							clearable
							size="medium"
							style="width: 200px"
							:placeholder="$t('common.please_enter')"
						></el-input>
					</el-form-item>
					<!-- <el-form-item>
						<el-input
							v-model="queryData.name"
							clearable
							size="medium"
							:placeholder="$t('common.please_enter')"
						>
							<el-select
								slot="prepend"
								v-model="queryData.nameType"
								style="width: 120px"
								:placeholder="$t('common.please_choose')"
							>
								<el-option
									:label="$t('agent.agent_account')"
									:value="1"
								></el-option>
								<el-option
									:label="$t('agent.total_agent_account')"
									:value="2"
								></el-option>
							</el-select>
						</el-input>
					</el-form-item> -->
					<!-- <el-form-item>
						<el-radio-group
							v-model="queryData.isAllSub"
							:disabled="!queryData.name"
						>
							<span @click="handleIsAllSubChange(false)" style="margin: 0 10px;">
								<el-radio :label="false">
								{{ $t('agent.direct_sub_level') }}
								</el-radio>
							</span>
							<span @click="handleIsAllSubChange(true)">
								<el-radio :label="true">{{ $t('agent.all_sub_level') }}</el-radio>
							</span>
						</el-radio-group>
					</el-form-item> -->
					<el-form-item label="合营码">
						<el-input
							v-input="{ name: 'symbols' }"
							v-model="queryData.joinCode"
							:maxlength="11"
							clearable
							size="medium"
							style="width: 200px"
							:placeholder="$t('common.please_enter')"
						></el-input>
					</el-form-item>
					<!-- 账号类型 -->
					<el-form-item :label="$t('agent.account_type') + ':'">
						<el-select
							v-model="queryData.accountType"
							size="medium"
							:placeholder="$t('common.all')"
							clearable
							multiple
							collapse-tags
						>
							<el-option
								v-for="item in accountTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('common.account_status') + ':'">
						<el-select
							v-model="queryData.accountStatus"
							size="medium"
							:placeholder="$t('common.all')"
							clearable
							collapse-tags
						>
							<el-option
								v-for="item in accountStatusArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<!--<el-form-item :label="$t('agent.credit_level') + ':'">
						<el-select
							v-model="queryData.creditLevel"
							size="medium"
							:placeholder="$t('common.all')"
							clearable
						>
							<el-option
								v-for="item in creditLevelList"
								:key="item"
								:label="item"
								:value="item"
							></el-option>
						</el-select>
					</el-form-item>-->
					<el-form-item
						:label="$t('common.register_device') + ':'"
						class="tagheight"
					>
						<el-select
							v-model="queryData.registerDeviceType"
							clearable
							:placeholder="$t('common.all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="item in appIdArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.entrance_role') + ':'">
						<el-select
							v-model="queryData.entryAuthority"
							clearable
							size="medium"
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in entrAuthorityTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<!-- <el-form-item label="分润模式:">
						<el-select
							v-model="queryData.commissionMode"
							clearable
							size="medium"
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in commissionModeTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item> -->
					<!-- TODO: Change the businessModel -->
					<el-form-item
						:label="`${$t('common.business_model')}:`"
						label-width="77px"
					>
						<business-model-selector
							:hideAllModel="false"
							v-model="queryData.businessModel"
							:value="queryData.businessModel"
						/>
					</el-form-item>
					<el-form-item
						:label="`${$t('agent.top_proxy_belong')}:`"
						label-width="77px"
					>
						<el-input
							v-model="queryData.proxyAffiliation"
							class="input-with-select"
							:placeholder="$t('common.please_enter')"
							clearable
							size="medium"
							v-input="{name: 'onlyInputNumZh'}"
						></el-input>
					</el-form-item>
					<el-form-item :label="'总代分组:'">
						<el-select
							v-model="queryData.groupIdList"
							clearable
							multiple
							collapse-tags
							size="medium"
							:placeholder="$t('common.all')"
						>
							<el-option
								v-for="item in groupList"
								:key="item.id"
								:label="item.groupName"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('agent.agent_level') + ':'">
					<el-select
						v-model="queryData.proxyLevelList"
						style="width: 120px"
						clearable
						multiple
						collapse-tags
						:placeholder="$t('common.all')"
					>
						<el-option
							v-for="item in proxyLevels"
							:key="item.id"
							:label="item.id"
							:value="item.id"
						></el-option>
					</el-select>
				</el-form-item>
					<el-form-item style="margin-left: 3px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							:loading="loading"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset(false)"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('201011')"
							type="warning"
							icon="el-icon-download"
							size="medium"
							:disabled="exportLoading"
							:loading="exportLoading"
							@click="exportExcel"
						>
							{{ $t('common.export') }}
						</el-button>
					</el-form-item>
				</el-form>

				<el-row style="width: 480px;" class="agentCheckList">
					<el-col :span="3" class="agent-label">代理：</el-col>
					<el-col :span="4">
						<el-checkbox
							@change="handleAgentCheck"
							label="all"
							:value="agentCheckAll"
						>
							全选
						</el-checkbox>
					</el-col>
					<el-checkbox-group v-model="agentCheckVals">
						<el-checkbox
							v-for="(v, k) in agentCheckList"
							:label="k"
							:key="k"
						>
							{{ v }}
						</el-checkbox>
					</el-checkbox-group>
				</el-row>
			</template>
			<template slot="content">
				<MemberProxyBatch
					userType="proxy"
					:loading="loading"
					creditPermissionId="90360057"
					accountPermissionId="90360058"
					:isShowBatch.sync="isShowBatch"
					:batchUserList="batchUserList"
					@resetBatchUser="resetBatchUser"
					@loadData="loadData"
				/>
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="dataList"
					style="width: 100%"
					:header-cell-style="getRowClass"
					highlight-current-row
					:max-height="tableHeight"
					ref="dataTable"
					@select="handleSelectionChange"
					@select-all="handleSelectionChange"
				>
					<el-table-column
						v-if="isShowBatch"
						type="selection"
						align="center"
						width="80"
					></el-table-column>
					<el-table-column
						key="userName"
						prop="userName"
						align="center"
						:label="$t('agent.agent_account')"
						min-width="150"
					>
						<template slot-scope="scope">
							<Copy
								v-if="!!scope.row.userName"
								:title="scope.row.userName"
								:copy="copy"
							>
								{{ scope.row.userName }}
							</Copy>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="proxyAffiliation"
						align="center"
						:label="$t('agent.top_proxy_belong')"
						min-width="150"
					>
						<template slot-scope="scope">
							<span>
								{{ scope.row.proxyAffiliation || '-' }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						key="joinCode"
						prop="joinCode"
						align="center"
						label="合营码"
						min-width="150"
					>
						<template slot-scope="scope">
							{{ scope.row.joinCode || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						key="proxyLevel"
						align="center"
						min-width="200"
						:label="$t('agent.level_name')"
						prop="proxyLevelproxyLevelName"
					>
						<template slot="header">
							{{ $t('agent.agent_level') }}
							<br />
							{{ $t('agent.level_name') }}
						</template>
						<template slot-scope="scope">
							<div>
								<span v-if="scope.row.entryAuthority === 0">
									-
								</span>
								<span v-else>
									{{
										(scope.row.proxyLevel === 0
											? '0'
											: scope.row.proxyLevel) || '-'
									}}
								</span>
							</div>
							<div>
								<span v-if="scope.row.entryAuthority === 0">
									-
								</span>
								<span v-else>
									{{ scope.row.proxyLevelName || '-' }}
								</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						:label="$t('common.belong_merchant')"
						width="120"
					>
						<template slot-scope="scope">
							{{ merchantFilter(scope.row.merchantId) }}
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						:label="'总代分组'"
						width="120"
					>
						<template slot-scope="scope">
							{{ scope.row.groupName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						key="parentProxyName"
						prop="parentProxyName"
						align="center"
						:label="$t('common.direct_superior')"
						min-width="110"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.parentProxyName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						key="topProxyName"
						prop="topProxyName"
						align="center"
						:label="$t('agent.total_agent_account')"
						min-width="110"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.topProxyName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						key="accountType"
						prop="accountType"
						align="center"
						:label="$t('common.number_type')"
						min-width="110"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.accountType">
								{{
									typeFilter(
										scope.row.accountType,
										'accountType'
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<!-- <el-table-column
						key="commissionMode"
						prop="commissionMode"
						align="center"
						label="分润模式"
						min-width="110"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.commissionMode">
								{{
									typeFilter(
										scope.row.commissionMode,
										undefined,
										commissionModeTypeArr
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column> -->
					<el-table-column
						prop="businessModel"
						align="center"
						:label="`${$t('common.business_model')}`"
						min-width="100"
					>
						<template slot-scope="scope">
							{{
								mappingBusinessModel(scope.row.businessModel) ||
									'-'
							}}
						</template>
					</el-table-column>
					<el-table-column
						key="labelName"
						prop="labelName"
						align="center"
						:label="$t('agent.agent_label')"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.labelName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="windControlName"
						align="center"
						:label="$t('common.risk_control_level')"
						min-width="110"
					>
						<template slot-scope="scope">
							<span>
								{{
									scope.row.windControlName ||
										matchvipDict(scope.row.windControlId) ||
										'-'
								}}
							</span>
						</template>
					</el-table-column>

					<el-table-column
						key="accountStatus"
						prop="accountStatus"
						align="center"
						:label="$t('common.account_status')"
						min-width="115"
					>
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.liquidationStatus === 1 ||
										scope.row.liquidationStatus === 2
								"
								class="disableRgba"
							>
								{{ $t('agent.liquidation') }}
							</span>
							<span v-else>
								<span
									v-if="!!scope.row.paymentLockStatus"
									class="deleteRgba"
								>
									{{ $t('agent.charge_lock') }}
									<br />
								</span>
								<span v-if="false">
									{{ $t('agent.login_lock') }}：
								</span>
								<span
									v-if="!!scope.row.loginLockStatus"
									class="disableRgba"
								>
									{{ $t('agent.login_lock') }}
								</span>
								<span
									v-if="!!scope.row.gameLockStatus"
									class="lockingRgba"
								>
									{{ $t('agent.game_lock') }}
								</span>
								<span
									v-if="
										scope.row.loginLockStatus === 0 &&
											scope.row.paymentLockStatus === 0
									"
									class="normalRgba"
								>
									{{ $t('agent.normal') }}
								</span>
							</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="creditLevel"
						align="center"
						:label="$t('agent.credit_level')"
						min-width="110"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.creditLevel ||
										scope.row.creditLevel === 0
								"
							>
								{{ scope.row.creditLevel }}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						key="entryAuthority"
						prop="entryAuthority"
						align="center"
						:label="$t('agent.entrance_role')"
						min-width="120"
					>
						<template slot-scope="scope">
							{{
								typeFilter(
									scope.row.entryAuthority,
									'entrAuthorityType'
								)
							}}
						</template>
					</el-table-column>
					<!-- 契约模式 -->
					<!-- <el-table-column
						key="contractModel"
						prop="contractModel"
						align="center"
						:label="$t('agent.contract_mode')"
						min-width="120"
					>
						<template slot-scope="scope">
							{{ typeFilter(scope.row.contractModel, 'contractModule') }}
						</template>
					</el-table-column> -->
					<!-- 是否有欠款 -->
					<!-- <el-table-column
						key="debtStatus"
						prop="debtStatus"
						align="center"
						:label="$t('agent.is_debt')"
						min-width="120"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.debtStatus === 1" class="redColor">
								{{ $t('agent.has_debt') }}
							</span>
							<span v-else-if="scope.row.debtStatus === 0" class="enableColor">
								{{ $t('agent.no_arrears') }}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column> -->

					<!-- <el-table-column
						key="rebateSum"
						prop="rebateSum"
						align="center"
						label="累计个人返点"
						min-width="170"
					>
						<template slot-scope="scope">
							<span>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.rebateSum
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						key="CommissionSum"
						prop="CommissionSum"
						align="center"
						label="累计团队分成"
						min-width="170"
					>
						<template slot-scope="scope">
							{{
								handleNumber(
									scope.row.currency,
									scope.row.CommissionSum
								)
							}}
						</template>
					</el-table-column> -->

					<el-table-column
						key="underMemberNum"
						prop="underMemberNum"
						align="center"
						:label="$t('agent.sub_agent_numbers')"
						min-width="130"
					>
						<template slot="header">
							{{ $t('agent.sub_agent_numbers') }}
							<br />
							{{ $t('agent.sub_member_numbers') }}
						</template>
						<template slot-scope="scope">
							{{ scope.row.underProxyNum || '0' }}
							<br />
							{{ scope.row.underMemberNum || '0' }}
						</template>
					</el-table-column>
					<el-table-column
						key="directlyUnderProxyNum"
						prop="directlyUnderProxyNum"
						align="center"
						:label="$t('agent.direct_agent_number')"
						min-width="130"
					>
						<template slot="header">
							{{ $t('agent.direct_agent_number') }}
							<br />
							{{ $t('agent.direct_member_number') }}
						</template>
						<template slot-scope="scope">
							{{ scope.row.directlyUnderProxyNum || '0' }}
							<br />
							{{ scope.row.directlyUnderMemberNum || '0' }}
						</template>
					</el-table-column>
					<!-- <el-table-column
						key="commissionBalance"
						align="center"
						min-width="120"
						:label="$t('agent.quota_wallet_balance')"
					>
						<template slot="header">
							{{ $t('agent.commission_wallet_balance') }}
							<br />
							{{ $t('agent.quota_wallet_balance') }}
						</template>
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.commissionBalance ||
										scope.row.commissionBalance === 0
								"
							>
                                {{ handleCurrency(scope.row.currency) }}
                                {{ handleNumber(scope.row.currency, scope.row.commissionBalance) }}
							</span>
							<span v-else>0</span>
							<br />
							<span
								v-if="scope.row.proxyBalance || scope.row.proxyBalance === 0"
							>
                                {{ handleCurrency(scope.row.currency) }}
                                {{ handleNumber(scope.row.currency, scope.row.proxyBalance) }}
							</span>
							<span v-else>0</span>
						</template>
					</el-table-column> -->
					<el-table-column
						key="totalDepositAmount"
						align="center"
						min-width="200"
						:label="$t('agent.total_deposit_times')"
					>
						<template slot="header">
							{{ $t('agent.total_deposit_amount') }}
							<br />
							{{ $t('agent.total_deposit_times') }}
						</template>
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.totalDepositAmount ||
										scope.row.totalDepositAmount === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.totalDepositAmount
									)
								}}
							</span>
							<span v-else>0</span>
							<br />
							<span
								v-if="
									scope.row.totalDepositNum ||
										scope.row.totalDepositNum === 0
								"
							>
								{{ scope.row.totalDepositNum }}
							</span>
							<span v-else>0</span>
						</template>
					</el-table-column>
					<el-table-column
						key="totalWithdrawAmount"
						align="center"
						min-width="200"
						:label="$t('agent.total_withdrawal_times')"
					>
						<template slot="header">
							{{ $t('agent.total_withdrawal_amount') }}
							<br />
							{{ $t('agent.total_withdrawal_times') }}
						</template>
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.totalWithdrawAmount ||
										scope.row.totalWithdrawAmount === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.totalWithdrawAmount
									)
								}}
							</span>
							<span v-else>0</span>
							<br />
							<span
								v-if="
									scope.row.totalWithdrawNum ||
										scope.row.totalWithdrawNum === 0
								"
							>
								{{ scope.row.totalWithdrawNum }}
							</span>
							<span v-else>0</span>
						</template>
					</el-table-column>
					<el-table-column
						key="centerWalletBalance"
						prop="centerWalletBalance"
						align="center"
						label="现金钱包余额"
						min-width="200"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.centerWalletBalance ||
										scope.row.centerWalletBalance === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.centerWalletBalance
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<!-- DXCD-1152 -->
					<el-table-column
						key="profit"
						prop="profit"
						align="center"
						label="收益钱包余额"
						min-width="200"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.profit ||
										scope.row.profit === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.profit
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="creditWalletBalance"
						align="center"
						label="可用额度"
						min-width="200"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.creditWalletBalance ||
										scope.row.creditWalletBalance === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.creditWalletBalance
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="borrowAmount"
						align="center"
						label="应还借款"
						min-width="200"
					>
						<template slot-scope="scope">
							<span>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.borrowAmount
									)
								}}
							</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="dispatchAmount"
						align="center"
						label="外放额度"
						min-width="200"
					>
						<template slot-scope="scope">
							<span>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.dispatchAmount
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="dispatchAmount"
						align="center"
						label="授信总额"
						min-width="200"
					>
						<template slot-scope="scope">
							<span>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.teamCreditTotal
									)
								}}
							</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="creditQuota"
						align="center"
						label="信用额度"
						min-width="200"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.creditQuota ||
										scope.row.creditQuota === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.creditQuota
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="accountsReceivable"
						align="center"
						label="应还账款"
						min-width="200"
					>
						<template slot-scope="scope">
							<span
								v-if="
									!!scope.row.accountsReceivable ||
										scope.row.accountsReceivable === 0
								"
							>
								{{ handleCurrency(scope.row.currency) }}
								{{
									handleNumber(
										scope.row.currency,
										scope.row.accountsReceivable
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>

					<el-table-column
						key="createDt"
						align="center"
						min-width="155"
						:label="$t('agent.date')"
						prop="proxyLevelproxyLevelName"
					>
						<template slot="header">
							{{ $t('common.register_time') }}
							<br />
							{{ $t('agent.last_login_time') }}
						</template>
						<template slot-scope="scope">
							{{ scope.row.createDt || '-' }}
							<br />
							{{ scope.row.lastLoginTime || '-' }}
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					v-show="!!total"
					class="pageValue"
					:current-page.sync="pageNum"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="$store.getters.pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
		</main-content>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
// import { UTable } from 'umy-ui'
import { routerNames } from '@/utils/consts'
import { filterEmptyParams } from '@/utils'
import MainContent from '../../../../components/MainContent/index.vue'
import BusinessModelSelector from '@/components/Form/BusinessModelSelector.vue'
import MemberProxyBatch from '@/components/MemberProxyBatch'
// const start = () =>
// 	dayjs()
// 		.startOf('day')
// 		.valueOf()
// const end = () =>
// 	dayjs()
// 		.endOf('day')
// 		.valueOf()

export default {
	name: routerNames.agentList,
	components: { MainContent, BusinessModelSelector, MemberProxyBatch },
	mixins: [list],
	data() {
		this.loadData = this.throttle(this.loadData, 1000)
		this._changeTableSort = this.throttle(this._changeTableSort, 1000)
		return {
			groupList: [],
			proxyLevels: [],
			isShowBatch: false,
			batchUserList: [],
			batchUserMap: new Map(),
			tableHeight: 480,
			otherDependenComponents: ['innerTab', 'addBtn'],
			agentCheckList: {
				'1': '自身',
				'2': '直属下级代理',
				'3': '全部下级代理'
			},
			agentCheckVals: ['1'],
			agentLoading: false,
			exportLoading: false,
			treeType: 'all', // all 全量代理树 search 搜索代理树
			treeSearchData: [],
			queryData: {
				proxyLevelList: undefined,
				groupIdList: undefined,
				commissionMode: undefined,
				// registerTime: [start(), end()],
				name: undefined,
				// accountType: [],
				accountStatus: undefined,
				windControlId: undefined,
				labelId: undefined,
				contractStatus: undefined,
				entryAuthority: 1,
				debtStatus: undefined,
				orderKey: undefined,
				orderType: undefined,
				bankerMode: '',
				timeType: 1,
				nameType: 1,
				isSelf: false,
				isAllSub: false,
				joinCode: undefined
			},
			selectSearchVal: '',
			selectSearchType: 1,
			dataList: [],
			total: 0,
			vipDict: [],
			userLabel: [],
			data: [],
			defaultProps: {
				children: 'childList',
				label: 'userName',
				isLeaf: 'leaf'
			},
			filterText: undefined,
			expandedKeys: [],
			summary: {},
			visible: false,
			creditLevelList: [], // 信用等级
			filterAccountQueryData: {
				nameType: 1,
				name: ''
			},
			filterAccountTypeArr: [
				{
					description: this.$t('agent.agent_account'),
					code: 1
				},
				{
					description: '商户名称',
					code: 2
				}
			],
			// 查询时间类型
			filterTimeTypeArr: [
				{
					description: this.$t('common.register_time'),
					code: 1
				},
				{
					description: this.$t('agent.last_login_time'),
					code: 2
				}
			],
			pageSize: 10
		}
	},
	computed: {
		agentCheckAll() {
			return this.agentCheckVals.length === 3
		},
		accountStatusArr() {
			return [
				{
					code: 1,
					description: this.$t('agent.normal')
				},
				{
					code: 2,
					description: this.$t('agent.login_lock')
				},
				{
					code: 3,
					description: this.$t('agent.charge_lock')
				},
				{
					code: 5,
					description: this.$t('agent.liquidation')
				}
			]
			// return this.globalDics.accountStatusType || []
		},
		accountTypeArr() {
			return this.globalDics.accountType || []
		},
		entrAuthorityTypeArr() {
			// return this.globalDics.entrAuthorityType || []
			return [
				{ code: 0, description: this.$t('agent.close') },
				{ code: 1, description: this.$t('common.turn_on') }
			]
		},
		commissionModeTypeArr() {
			// return this.globalDics.entrAuthorityType || []
			return [
				{ code: 1, description: '返点模式' },
				{ code: 2, description: '返佣模式' }
			]
		},
		contractStatusArr() {
			return this.globalDics.contractStatus || []
		},
		debtStatusArr() {
			return this.globalDics.debtStatus || []
		},
		appIdArr() {
			return this.globalDics.deviceType || []
		}
	},
	watch: {
		'filterAccountQueryData.name': function(newV, oldV) {
			if (!newV) {
				this.treeType = 'all'
			}
		},
		agentCheckVals: function(newV, oldV) {
			this.queryData.isSelf = newV.includes('1')
			this.queryData.isAllSub = newV.includes('3')
			// 会造成刷新两次列表
			// this.loadData()
		}
	},
	created() {
		// this.getMerchantDict()
	},
	mounted() {
		this.getWindControllerLevelDict()
		// this.getAgentLevelList()
		this.agentLoading = true // 首次加载显示树刷新图标
		this.getCreditLevelList()
		// this.initIndexDB('agentList', this.agentList)
		this.getGroupList()
		this.getProxyLevels()
	},
	methods: {
		getProxyLevels() {
			this.$api.getProxylevelnameList().then((res) => {
				this.proxyLevels = res.data || []
			})
		},
		async getGroupList() {
			try {
				const res = await this.$api
				.proxyGroupPageProxyGroup({
					pageNum: 1,
					pageSize: 999
				})

				this.groupList =res?.data?.record || []
			} catch (err) {
				console.log(err)
			}
		},
		resetBatchUser() {
			this.batchUserMap.clear()
			this.batchUserList = []
		},
		setBatchRowSelect() {
			if (!this.isShowBatch) return
			this.$refs.dataTable.$nextTick((_) => {
				this.dataList.forEach((item, index) => {
					const flag = this.batchUserList.find(
						(row) => row.userName == item.userName
					)
					if (flag) {
						this.$refs.dataTable.toggleRowSelection(
							this.dataList[index],
							true
						)
					}
				})
			})
		},
		handleSelectionChange(val, row) {
			this.dataList.forEach((item) => {
				const checkItem = val.find(
					(row) =>
						row.userName === item.userName &&
						row.merchantId === item.merchantId
				)
				const mapKey = item.userName + '-' + item.merchantId
				if (checkItem) {
					this.batchUserMap.set(mapKey, {
						userName: item.userName,
						merchantId: item.merchantId
					})
				} else {
					this.batchUserMap.delete(mapKey)
				}
			})
			this.batchUserList = [...this.batchUserMap.values()]
		},
		search() {
			this.pageNum = 1
			this.isShowBatch = false
			this.resetBatchUser()
			this.loadData()
		},
		loadData() {
			const create = this.queryData.registerTime || []
			const [startTime, endTime] = create

			let params = {
				...this.queryData,
				timeStart: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				timeEnd: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			params = {
				...this.getParams(params)
			}

			this.dataList = []
			this.loading = true
			delete params.registerTime
			params.isAllSub = this.agentCheckVals?.includes('3')
			params.isSelf = this.agentCheckVals?.includes('1')

			if (
				!params.name ||
				(!this.agentCheckVals.includes('3') &&
					!this.agentCheckVals.includes('2'))
			) {
				delete params.isAllSub
			}

			if (params.name && this.agentCheckVals.length === 0) {
				this.loading = false
				return
			}
			if (params.businessModel === '') {
				delete params.businessModel
			}
			this.$api
				.AgentListAPI(filterEmptyParams(params))
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						const { record, totalRecord } = res.data || {}
						this.dataList = Array.isArray(record)
							? Object.freeze(record)
							: []
						this.total = totalRecord || 0
						this.setBatchRowSelect()
					} else {
						this.$message({
							message: res?.msg,
							type: 'error'
						})
					}
				})
				.catch(() => (this.loading = false))
		},
		// 获取代理标签
		getMerchantDict() {
			this.$api.agentDictAPI().then((res) => {
				if (res?.code === 200) {
					this.userLabel = res.data || []
				} else {
					this.$message({
						message: res?.msg,
						type: 'error'
					})
				}
			})
		},
		// 代理列表树形结构, 没搜出来哪里用到，先注释
		// getAgentLevelList() {
		// 	this.agentLoading = true
		// 	this.$api.AgentLevelListAPI().then((res) => {
		// 		this.agentLoading = false
		// 		if (res?.code === 200) {
		// 			this.data = res.data
		// 		}
		// 	})
		// },
		getCreditLevelList() {
			this.$api
				.getCreditLevelConfcreditList({ creditType: 2 })
				.then((res) => {
					if (res?.code === 200) {
						this.creditLevelList = res.data || []
					}
				})
		},
		// 搜索下级
		searchUnderAgent() {
			if (!this.filterAccountQueryData.name) return
			this.agentLoading = true
			this.treeType = undefined
			this.$api
				.AgentLevelLinkByUserNameAPI(this.filterAccountQueryData)
				.then((res) => {
					this.agentLoading = false
					this.treeType = 'search'
					if (res?.code === 200) {
						const keys = res.data.map((item) => item.id)
						this.expandedKeys = keys
					}
				})
				.catch((wee) => {
					this.treeType = 'search'
					this.agentLoading = false
				})
		},
		reset(data) {
			this.pageNum = 1
			this.pageSize = 10
			this.queryData = {
				// registerTime: data ? undefined : [start(), end()],
				// name: data.userName || undefined,
				isAllSub: data ? true : undefined,
				// accountType: [],
				// accountStatus: undefined,
				// windControlId: undefined,
				// labelId: undefined,
				// contractStatus: undefined,
				entryAuthority: 1,
				// debtStatus: undefined,
				// orderKey: undefined,
				// orderType: undefined
				timeType: 1,
				nameType: 1,
				name: data.userName || undefined
			}
			this.agentCheckVals = ['1']
			this.$refs['form'].resetFields()
			this.isShowBatch = false
			this.resetBatchUser()
			this.loadData(data)
		},
		nodeClick(data, node) {
			// 点击顶级节点时，动态更新下级数据
			if (this.treeType === 'all' && node.level === 1) {
				const cnode = this.$refs.tree.getNode(data.id)
				cnode.loaded = false
				cnode.expand()
			}
			this.reset(data)
		},

		async loadNode(node, resolve) {
			this.$api
				.AgentLevelListAPI()
				.then((res) => {
					if (res?.code === 200) {
						if (node.level === 0) {
							return resolve(res.data || [])
						} else {
							this.$api
								.AgentLevelLinkAPI({
									id: node.data.id,
									merchantId: node.data.merchantId
								})
								.then((res) => {
									if (res?.code === 200) {
										const { childList } = res.data || {}
										if (childList) {
											return resolve(childList)
										} else {
											return resolve([])
										}
									}
								})
							return resolve([]) // 防止该节点没有子节点时一直转圈的问题出现
						}
					}
				})
				.finally(() => {
					this.agentLoading = false
				})
		},
		async loadNode2(node, resolve) {
			this.$api
				.AgentLevelLinkByUserNameAPI(this.filterAccountQueryData)
				.then((res) => {
					if (res?.code === 200) {
						if (node.level === 0) {
							return resolve(res.data || [])
						} else {
							this.$api
								.AgentLevelLinkAPI({
									id: node.data.id,
									merchantId: node.data.merchantId
								})
								.then((res) => {
									if (res?.code === 200) {
										const { childList } = res.data || {}
										if (childList) {
											return resolve(childList)
										} else {
											return resolve([])
										}
									}
								})
							return resolve([]) // 防止该节点没有子节点时一直转圈的问题出现
						}
					}
				})
		},
		_changeTableSort({ column, prop, order }) {
			const obj = {
				underProxyNum: 1,
				underMemberNum: 2,
				directlyUnderProxyNum: 3,
				directlyUnderMemberNum: 4,
				lastLoginTime: 5,
				createDt: 6
			}
			this.queryData.orderKey = obj[prop]
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},

		getSummaries(param) {
			const { columns, data } = param
			const sums = []
			const arr = [
				this.$t('agent.direct_agent_number'),
				this.$t('agent.direct_member_number')
			]
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = (
						<div class='count_row'>
							<p>$t('agent.subtotal')</p>
						</div>
					)
					return
				} else if (arr.includes(column.label)) {
					const values = data.map((item) => {
						return Number(item[column.property])
					})
					if (!values.every((value) => isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr)
							if (!isNaN(value)) {
								return prev + curr
							} else {
								return prev
							}
						}, 0)
					} else {
						sums[index] = (
							<div class='count_row'>
								<p>-</p>
							</div>
						)
					}
					return
				} else {
					sums[index] = (
						<div class='count_row'>
							<p />
						</div>
					)
				}
			})

			return sums
		},
		// 获取风控层级
		getWindControllerLevelDict() {
			this.$api
				.getSelectWindControlLevel({ windControlType: 2 })
				.then((res) => {
					if (res?.code === 200) {
						this.vipDict = res.data || []
					}
				})
		},
		matchvipDict(id) {
			const result = this.vipDict.find((item) => item.id === id)
			if (result) {
				return result.windControlLevelName
			} else {
				return '-'
			}
		},
		renderContent(h, { node, data, store }) {
			return (
				<span class='custom-tree-node'>
					<span>
						<i className='el-icon-folder' />
						{node.label}
					</span>
				</span>
			)
			// <span>
			// 	<el-button size='mini' type='text' on-click={() => {}}>
			// 		&nbsp;
			// 	</el-button>
			// </span>
		},
		exportExcel() {
			const create = this.queryData.registerTime || []
			const [startTime, endTime] = create

			let params = {
				...this.queryData,
				timeStart: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				timeEnd: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			params = {
				...this.getParams(params)
			}
			delete params.registerTime
			params.isAllSub = this.agentCheckVals?.includes('3')
			params.isSelf = this.agentCheckVals?.includes('1')

			if (
				!params.name ||
				(!this.agentCheckVals.includes('3') &&
					!this.agentCheckVals.includes('2'))
			) {
				delete params.isAllSub
			}
			this.exportLoading = true
			this.exportExcelPublic({
				api: 'agentListExportAPI',
				params
			}).finally(() => {
				this.exportLoading = false
			})
			// this.$confirm(
			// 	`<strong>${this.$t(
			// 		'common.is_export'
			// 	)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
			// 		'common.excess_data'
			// 	)}</span>`,
			// 	this.$t('common.success_tip'),
			// 	{
			// 		dangerouslyUseHTMLString: true,
			// 		confirmButtonText: this.$t('common.confirm'),
			// 		cancelButtonText: this.$t('common.cancel'),
			// 		type: 'warning'
			// 	}
			// )
			// 	.then(() => {
			// 		let errMsg = this.$t('common.export_err')
			// 		this.$api
			// 			.agentListExportAPI(params)
			// 			.then((res) => {
			// 				this.loading = false
			// 				if (res?.status === 200) {
			// 					const { type = [], msg } = res.data || {}
			// 					errMsg = msg
			// 					if (type.includes('application/json')) {
			// 						const reader = new FileReader()
			// 						reader.onload = (evt) => {
			// 							if (evt?.target?.readyState === 2) {
			// 								const ret = JSON.parse(
			// 									evt.target.result
			// 								)
			// 								if (ret?.code !== 200) {
			// 									this.$message({
			// 										type: 'error',
			// 										message: ret.msg,
			// 										duration: 1500
			// 									})
			// 								}
			// 							}
			// 						}
			// 						reader.readAsText(res.data)
			// 					} else {
			// 						const result = res.data
			// 						const disposition =
			// 							res.headers['content-disposition']
			// 						const fileNames =
			// 							disposition && disposition.split("''")
			// 						let fileName = fileNames[1]
			// 						fileName = decodeURIComponent(fileName)
			// 						const blob = new Blob([result], {
			// 							type: 'application/octet-stream'
			// 						})
			// 						if (
			// 							'download' in
			// 							document.createElement('a')
			// 						) {
			// 							const downloadLink = document.createElement(
			// 								'a'
			// 							)
			// 							downloadLink.download = fileName || ''
			// 							downloadLink.style.display = 'none'
			// 							downloadLink.href = URL.createObjectURL(
			// 								blob
			// 							)
			// 							document.body.appendChild(downloadLink)
			// 							downloadLink.click()
			// 							URL.revokeObjectURL(downloadLink.href)
			// 							document.body.removeChild(downloadLink)
			// 						} else {
			// 							window.navigator.msSaveBlob(
			// 								blob,
			// 								fileName
			// 							)
			// 						}
			// 						this.$message({
			// 							type: 'success',
			// 							message: this.$t(
			// 								'common.export_success'
			// 							),
			// 							duration: 1500
			// 						})
			// 					}
			// 				}
			// 			})
			// 			.catch(() => {
			// 				this.loading = false
			// 				this.$message({
			// 					type: 'error',
			// 					message: errMsg,
			// 					duration: 1500
			// 				})
			// 			})

			// 		setTimeout(() => {
			// 			this.loading = false
			// 		}, 1500)
			// 	})
			// 	.catch(() => {
			// 		this.loading = false
			// 	})
		},
		// handleIsAllSubChange(bool) {
		// 	if (bool === this.queryData.isAllSub) {
		// 		setTimeout(() => {
		// 			this.queryData.isAllSub = undefined
		// 		})
		// 	}
		// },
		handleAgentCheck(bool, e) {
			// all
			if (e.target.value === 'all') {
				if (bool) {
					this.agentCheckVals = Object.keys(this.agentCheckList)
				} else {
					this.agentCheckVals = []
				}
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.agentList-container {
	position: relative;
	min-height: calc(100vh - 130px);
	margin: 24px 0 0;
	.tree-container {
		position: absolute;
		left: 0;
		top: 0;
		width: 330px;
		// overflow-x: scroll;
		// height: 660px;
		border-bottom: 1px solid #ebeef5;
		.filter-search-box {
			width: 100%;
			height: 45px;
			position: relative;
			::v-deep .filter-search-text {
				width: 200px;
			}
			::v-deep .filter-search-btn {
				min-width: 0;
				width: 65px;
			}
		}
		.filter-search-box:after {
			display: table;
			content: '.';
			clear: both;
		}
	}
	.view-container.dealer-container {
		margin-left: 330px;
	}
}
.tree-box {
	width: 320px;
	margin-right: 25px;
	height: calc(100vh - 242px);
	overflow-y: auto;
	overflow-x: auto;
}
.agentList-container:after {
	display: table;
	content: '.';
	clear: both;
}
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .el-tree-node__expand-icon {
	color: #c15353;
}
::v-deep .el-tree-node {
	padding-bottom: 4px;
	padding-top: 4px;
}
::v-deep .custom-tree-node .el-icon-s-custom {
	display: inline-block;
	width: 18px;
	height: 18px;
}
::v-deep .el-icon-user-solid {
	color: #c15353;
}
.el-tree {
	::v-deep .el-icon-caret-right:before {
		// 未展开
		content: '\e6d9';
		font-size: 18px;
	}
	::v-deep .expanded:before {
		// 展开
		content: '\e6d8';
		font-size: 18px;
	}
	::v-deep .expanded {
		// 展开不旋转
		-webkit-transform: rotate(0deg);
		transform: rotate(0deg);
	}
}
.setting-div {
	display: inline-block;
	margin-right: 10px;
}
.snap-form-item {
	::v-deep .el-form-item__content {
		display: flex;
		align-items: center;
		line-height: inherit;
	}
	::v-deep .el-range-editor.el-input__inner {
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
		margin-left: -4px;
	}
	::v-deep .el-select .el-input__inner {
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
		border-right: none;
	}
}
::v-deep .el-input-group__prepend {
	background-color: #fff;
}
.agent-label {
	font-size: 14px;
	color: #606266;
	font-weight: 600;
	width: 9.5%;
}
::v-deep
	.el-table__header
	.el-table-column--selection
	.cell
	.el-checkbox:after {
	content: '全选';
	font-size: 12px;
	margin-right: -25px;
	margin-left: 5px;
}
</style>
